<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        *{
            margin: 0;
            padding: 0;
        }
        h3{
            text-align: center;
        }
        table{
            border-collapse: collapse;
            border: 1px solid black;
            width: 50vw;
            height: 50vh;
            margin: 10vh auto;
        }
        td{
            border: 1px solid black;
        }
    </style>
</head>
<body>
    <h2>测试用</h2>
    <p>
        <h3>添加新用户</h3>
        账号：<input type="text" name="account" id="account">
        密码：<input type="text" name="password" id="password">
        <button onclick="addUser()">添加用户</button>
    </p>
    <!-- 用户列表 -->
    <p>
        <table>
            <tr>
                <th>ID</th>
                <th>账号</th>
                <th>密码</th>
                <th>操作</th>
            </tr>
            {% for u in users%}
            <tr>
                <td>{{u.id}}</td>
                <td>{{u.account}}</td>
                <td>{{u.password}}</td>
                <td><button onclick="rmUser('{{u.id}}')">删除</button></td>
            </tr>
            {% endfor%}
        </table>
    </p>
    <script>
        var account = document.getElementById('account');
        var password = document.getElementById('password');
        
        account.onkeydown = (e=>{
            if(e.key == "Enter"){
                password.focus()
            }
        })
        password.onkeydown = (e=>{
            if(e.key == "Enter"){
                addUser()
            }
        })


        function addUser(){
            if(account.value.length <= 0||password.value.length <= 0){
                return alert('表单不完整')
            }
            let user = {
                account:account.value,
                password:password.value
            }
            console.log(user);
            
            let xhr = new XMLHttpRequest();
            xhr.open('POST','/addUser',true);
            xhr.setRequestHeader('Content-Type', 'application/json');
            xhr.send(JSON.stringify(user));
            xhr.onreadystatechange = function(){
                if(xhr.readyState == 4 && xhr.status == 200){
                    console.log(xhr.responseText);
                    location.reload();
                }
            }
        }
        function rmUser(ID){
            console.log('dcsdc');
            console.log("删除事件"+ID);
            let send = new XMLHttpRequest();
            send.open('GET','/rm?id='+ID);
            send.send();
            send.onreadystatechange = function(){
                if(send.readyState == 4 && send.status == 200){
                    console.log(send.responseText);
                    location.reload()
                }
            }
        }
    </script>
</body>
</html>